package me.zhengjie.cron;

import cn.hutool.core.date.DateTime;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.config.NetConfig;
import me.zhengjie.config.RegisterAddressConfig;
import me.zhengjie.domain.PlcService;
import me.zhengjie.domain.ProInfoService;
import me.zhengjie.domain.UnbindingService;
import me.zhengjie.dto.sqlServer.PlcUnbinding;
import me.zhengjie.dto.sqlServer.ProductionInfo;
import me.zhengjie.modbusTCP.NoTwoUnbindingTCP;
import me.zhengjie.modbusTCP.UnbindingTCP;
import me.zhengjie.repository.PlcUnbindingRepository;
import me.zhengjie.util.AnalyseCodeScannerUtil;
import me.zhengjie.util.LoginUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutionException;

@Slf4j
@Component
@RequiredArgsConstructor
public class NoTwoUnbindingCron {

    private final UnbindingService unbindingService;
    private final ProInfoService proInfoService;
    private final PlcService plcService;
    private final NoTwoUnbindingTCP noTwoUnbindingTCP;
    private final PlcUnbindingRepository plcUnbindingRepository;
    private final AnalyseCodeScannerUtil analyseCodeScannerUtil;
    private final NetConfig netConfig;

    /**
     * 定时器定时读取
     * 拆解区扫码获取新的载盘信息
     * 更新plc新扫描到的载盘编码
     */
    @Scheduled(fixedDelay = 3000)
    public void getNewPalletCode(){
        try {
            Integer sensorValue = noTwoUnbindingTCP.readHoldingRegisters(RegisterAddressConfig.unbindingSensor);
            String i = noTwoUnbindingTCP.readHoldingRegistersString(RegisterAddressConfig.unbindingCodeScannerFirst);
            String j = noTwoUnbindingTCP.readHoldingRegistersString(RegisterAddressConfig.unbindingCodeScannerSecond);

            String scannerValue = analyseCodeScannerUtil.analyseCodeScanner(i,j);
            log.info("2号拆解区读值，传感器值：{}，扫码器值：{}",sensorValue,scannerValue);
            if (sensorValue!=null && sensorValue == 1 && scannerValue != null){
                PlcUnbinding plcUnbinding = plcService.getUnbindingStationByIp(netConfig.getNoTwoUnbindingPlcIp());
                plcUnbinding.setContent(scannerValue);
                plcUnbindingRepository.save(plcUnbinding);
                ProductionInfo proInfo = proInfoService.getNewUnbindingProductionInfo(scannerValue);
                // 开始记录拆解的生产信息
                proInfoService.startUnbinding("admin", DateTime.now().toTimestamp(), scannerValue, proInfo.getId() ,plcUnbinding.getUnbindingStation());
                noTwoUnbindingTCP.writeWithRetry(RegisterAddressConfig.unbindingIfSuccessReadCode,1,5);
            }

        } catch (Exception e) {
            log.error("2号拆解区定时器出错：{}",e.getMessage());
        }
    }

    @Scheduled(fixedDelay = 3000)
    public void unbindingSecondCron(){
        try {
            Integer endSensor = noTwoUnbindingTCP.readHoldingRegisters(RegisterAddressConfig.unbindingEndSensor);
            log.info("2号拆解区完成信号：{}",endSensor);
            if (endSensor !=null && endSensor == 1){

                PlcUnbinding plcUnbinding = plcService.getUnbindingStationByIp(netConfig.getNoTwoUnbindingPlcIp());
                String palletCode = plcUnbinding.getContent();
                /*unbindingService.unbinding(palletCode);*/

                // 删除该出库单明细（当只剩一条明细，解绑拆解单）
                unbindingService.deleteDetailOrFinishOrder(palletCode);

                ProductionInfo proInfo = proInfoService.getNewUnbindingProductionInfo(palletCode);
                // 记录拆解作业结束信息
                proInfoService.finishUnbinding(DateTime.now().toTimestamp(), palletCode, proInfo.getId());
                log.info("2号拆解台完成{}",palletCode);
                noTwoUnbindingTCP.writeWithRetry(RegisterAddressConfig.unbindingIfSuccessReadEndSensor,1, 5);
            }


        } catch (Exception e) {
            log.error("拆解区plc2异常，错误原因：{}",e.getMessage());
        }
    }
}
